//! # 分布式配置服务器
//!
//! 提供分布式配置中心的服务器端实现，采用面向接口编程设计，
//! 支持多环境配置管理、Git仓库集成、配置加密、审计日志等企业级功能。
//!
//! ## 设计原则
//!
//! * **面向接口编程** - 所有模块通过trait接口交互
//! * **依赖注入** - 通过构建器模式注入具体实现
//! * **高内聚低耦合** - 模块职责单一，接口清晰
//! * **可测试性** - 所有依赖都可模拟测试
//! * **可扩展性** - 支持插件化扩展
//!
//! ## 核心组件
//!
//! * [`ConfigurationServer`] - 配置服务器主控制器
//! * [`ConfigurationService`] - 配置服务核心业务逻辑
//! * [`ServerBuilder`] - 服务器构建器
//!
//! ## 快速开始
//!
//! ```rust,no_run
//! use rustcloud_config::server::*;
//! use rustcloud_config::core::*;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // 创建配置服务器
//! let server = ConfigurationServer::builder()
//!     .with_git_storage("./config-repo")
//!     .bind("0.0.0.0:8888".parse()?)
//!     .build()
//!     .await?;
//!
//! // 启动服务器
//! server.start().await?;
//! Ok(())
//! }
//! ```

pub mod api;
pub mod git;
pub mod storage;

// 🆕 新增：配置广播集成模块
#[cfg(feature = "broadcast")]
pub mod broadcast_integration;

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::SystemTime;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use tracing::{debug, info, warn, error};

use crate::core::*;
use crate::RustCloudConfig;

// 🆕 新增：导入配置广播相关功能
#[cfg(feature = "broadcast")]
use crate::broadcast::*;
#[cfg(feature = "broadcast")]
use crate::bus_broadcast::*;
use crate::broadcast::{ConfigBroadcaster, ConfigBroadcastManager};

// 基本类型定义
/// 配置响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigResponse {
    pub property_sources: Vec<PropertySource>,
    pub version: String,
    pub state: String,
    pub label: String,
}

/// 属性来源
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropertySource {
    pub name: String,
    pub source: HashMap<String, serde_json::Value>,
}

/// 配置变更记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigChangeRecord {
    pub id: String,
    pub application: String,
    pub profile: String,
    pub label: String,
    pub operation: String,
    pub user: String,
    pub timestamp: SystemTime,
    pub description: String,
    pub changes: HashMap<String, String>,
}

// 简化的trait定义（仅用于编译通过）
#[async_trait]
pub trait ConfigStorage: Send + Sync {
    async fn get_config(&self, environment: &ConfigEnvironment) -> ServerResult<ConfigResponse>;
    async fn save_config(&self, environment: &ConfigEnvironment, config: &RustCloudConfig, user: &str) -> ServerResult<String>;
    async fn delete_config(&self, environment: &ConfigEnvironment, user: &str) -> ServerResult<()>;
}

/// 配置服务器错误类型
#[derive(thiserror::Error, Debug)]
pub enum ConfigurationServerError {
    #[error("配置不存在: {application}:{profile}:{label}")]
    ConfigNotFound {
        application: String,
        profile: String,
        label: String,
    },
    
    #[error("存储错误: {0}")]
    StorageError(String),
    
    #[error("Git错误: {0}")]
    GitError(String),
    
    #[error("加密错误: {0}")]
    EncryptionError(String),
    
    #[error("权限错误: {0}")]
    AuthorizationError(String),
    
    #[error("权限错误: {0}")]
    PermissionError(String),
    
    #[error("服务器错误: {0}")]
    ServerError(String),
    
    #[error("IO错误: {source}")]
    IoError {
        #[from]
        source: std::io::Error,
    },
    
    #[error("序列化错误: {source}")]
    SerializationError {
        #[from] 
        source: serde_json::Error,
    },
}

impl From<Box<dyn std::error::Error + Send + Sync>> for ConfigurationServerError {
    fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
        Self::ServerError(err.to_string())
    }
}

/// 服务器操作结果类型别名
pub type ServerResult<T> = std::result::Result<T, ConfigurationServerError>;

/// 配置服务器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigurationServerConfig {
    /// 服务器监听地址
    pub bind_address: SocketAddr,
    /// 服务器名称
    pub server_name: String,
    /// 最大并发连接数
    pub max_connections: usize,
    /// 请求超时时间（秒）
    pub request_timeout: u64,
    /// 启用CORS
    pub enable_cors: bool,
    /// 缓存TTL（秒）
    pub cache_ttl: u64,
    /// 健康检查间隔（秒）
    pub health_check_interval: u64,
    /// 启用配置广播
    #[cfg(feature = "broadcast")]
    pub enable_broadcast: bool,
    /// 广播主题前缀
    #[cfg(feature = "broadcast")]
    pub broadcast_topic_prefix: Option<String>,
    /// Git仓库路径
    pub git_repo_path: Option<std::path::PathBuf>,
    /// Git仓库URL
    pub git_repo_url: Option<String>,
    /// Git用户名
    pub git_username: Option<String>,
    /// Git密码
    pub git_password: Option<String>,
}

impl Default for ConfigurationServerConfig {
    fn default() -> Self {
        Self {
            bind_address: "0.0.0.0:8888".parse().unwrap(),
            server_name: "RustCloud Config Server".to_string(),
            max_connections: 1000,
            request_timeout: 30,
            enable_cors: true,
            enable_auth: false,
            jwt_secret: None,
            cache_ttl: 300,
            audit_enabled: true,
            health_check_interval: 30,
            #[cfg(feature = "broadcast")]
            enable_broadcast: false,
            #[cfg(feature = "broadcast")]
            broadcast_topic_prefix: None,
            git_repo_path: None,
            git_repo_url: None,
            git_username: None,
            git_password: None,
        }
    }
}

/// 配置服务核心业务逻辑
/// 
/// 处理配置的增删改查，协调各个组件之间的交互
pub struct ConfigurationService {
    /// 存储层
    storage: Arc<dyn ConfigurationStorage>,
    /// 加密组件
    encryption: Option<Arc<dyn ConfigurationEncryption>>,
    /// 审计组件
    audit: Option<Arc<dyn ConfigurationAudit>>,
    /// 缓存组件
    cache: Option<Arc<dyn ConfigurationCache>>,
    /// 通知组件
    notifier: Option<Arc<dyn ConfigurationNotifier>>,
    /// 权限控制
    authorization: Option<Arc<dyn ConfigurationAuthorization>>,
    /// 健康检查
    health_check: Option<Arc<dyn ConfigurationHealthCheck>>,
    /// 配置广播管理器
    broadcast_manager: Option<Arc<dyn ConfigBroadcastManager>>,
    /// 统计信息
    stats: Arc<RwLock<ServiceStatistics>>,
}

/// 服务统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceStatistics {
    /// 已处理请求数
    pub requests_handled: u64,
    /// 当前连接数
    pub active_connections: u32,
    /// 成功请求数
    pub successful_requests: u64,
    /// 失败请求数
    pub failed_requests: u64,
    /// 平均处理时间（毫秒）
    pub avg_processing_time_ms: f64,
    /// 连接池统计
    pub connection_pool_stats: ConnectionPoolStats,
    /// 内存使用统计
    pub memory_stats: MemoryStats,
    /// 缓存统计
    pub cache_stats: CacheStats,
    /// 启动时间
    pub start_time: SystemTime,
    /// 最大并发连接数记录
    pub max_concurrent_connections: u32,
}

impl Default for ServiceStatistics {
    fn default() -> Self {
        Self {
            requests_handled: 0,
            active_connections: 0,
            successful_requests: 0,
            failed_requests: 0,
            avg_processing_time_ms: 0.0,
            connection_pool_stats: ConnectionPoolStats::default(),
            memory_stats: MemoryStats::default(),
            cache_stats: CacheStats::default(),
            start_time: SystemTime::now(),
            max_concurrent_connections: 0,
        }
    }
}

/// 连接池统计信息
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConnectionPoolStats {
    /// 当前活跃连接数
    pub active_connections: u32,
    /// 空闲连接数
    pub idle_connections: u32,
    /// 总连接数
    pub total_connections: u32,
    /// 连接创建次数
    pub connections_created: u64,
    /// 连接关闭次数
    pub connections_closed: u64,
    /// 连接超时次数
    pub connection_timeouts: u64,
    /// 平均连接获取时间（毫秒）
    pub avg_connection_acquire_time_ms: f64,
}

/// 内存使用统计
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MemoryStats {
    /// 当前内存使用量（字节）
    pub current_memory_usage: u64,
    /// 峰值内存使用量（字节）
    pub peak_memory_usage: u64,
    /// 缓存占用内存（字节）
    pub cache_memory_usage: u64,
    /// 垃圾回收次数
    pub gc_count: u32,
    /// 内存池分配次数
    pub allocations: u64,
    /// 内存池释放次数
    pub deallocations: u64,
}

/// 缓存统计信息
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CacheStats {
    /// 缓存命中次数
    pub hits: u64,
    /// 缓存未命中次数
    pub misses: u64,
    /// 缓存驱逐次数
    pub evictions: u64,
    /// 缓存大小
    pub size: u64,
    /// 缓存命中率
    pub hit_rate: f64,
}

impl ConfigurationService {
    /// 创建新的配置服务
    pub fn new(storage: Arc<dyn ConfigurationStorage>) -> Self {
        let mut stats = ServiceStatistics::default();
        stats.start_time = SystemTime::now();
        
        Self {
            storage,
            encryption: None,
            audit: None,
            cache: None,
            notifier: None,
            authorization: None,
            health_check: None,
            broadcast_manager: None,
            stats: Arc::new(RwLock::new(stats)),
        }
    }
    
    /// 设置加密组件
    pub fn with_encryption(mut self, encryption: Arc<dyn ConfigurationEncryption>) -> Self {
        self.encryption = Some(encryption);
        self
    }
    
    /// 设置审计组件
    pub fn with_audit(mut self, audit: Arc<dyn ConfigurationAudit>) -> Self {
        self.audit = Some(audit);
        self
    }
    
    /// 设置缓存组件
    pub fn with_cache(mut self, cache: Arc<dyn ConfigurationCache>) -> Self {
        self.cache = Some(cache);
        self
    }
    
    /// 设置通知组件
    pub fn with_notifier(mut self, notifier: Arc<dyn ConfigurationNotifier>) -> Self {
        self.notifier = Some(notifier);
        self
    }
    
    /// 设置权限控制组件
    pub fn with_authorization(mut self, authorization: Arc<dyn ConfigurationAuthorization>) -> Self {
        self.authorization = Some(authorization);
        self
    }
    
    /// 设置健康检查组件
    pub fn with_health_check(mut self, health_check: Arc<dyn ConfigurationHealthCheck>) -> Self {
        self.health_check = Some(health_check);
        self
    }
    
    /// 设置配置广播管理器
    pub fn with_broadcast_manager(mut self, broadcast_manager: Arc<dyn ConfigBroadcastManager>) -> Self {
        self.broadcast_manager = Some(broadcast_manager);
        self
    }
    
    /// 获取统计信息
    pub async fn get_statistics(&self) -> ServiceStatistics {
        self.stats.read().await.clone()
    }
    
    /// 获取详细统计信息
    pub async fn get_detailed_statistics(&self) -> ServiceStatistics {
        let mut stats = self.stats.read().await.clone();
        
        // 更新缓存统计
        if let Some(cache) = &self.cache {
            // 尝试获取缓存统计（需要在 ConfigurationCache trait 中添加相关方法）
            stats.cache_stats.size = cache.size().await.unwrap_or(0) as u64;
        }
        
        // 计算缓存命中率
        let total_cache_requests = stats.cache_stats.hits + stats.cache_stats.misses;
        if total_cache_requests > 0 {
            stats.cache_stats.hit_rate = stats.cache_stats.hits as f64 / total_cache_requests as f64;
        }
        
        stats
    }
    
    /// 内存优化：清理过期缓存
    pub async fn optimize_memory(&self) -> ServerResult<()> {
        if let Some(cache) = &self.cache {
            // 清理过期项
            let environments = cache.list_keys().await.unwrap_or_default();
            let mut cleaned_count = 0;
            
            for env in environments {
                if cache.is_expired(&env).await.unwrap_or(true) {
                    let _ = cache.remove(&env).await;
                    cleaned_count += 1;
                }
            }
            
            // 更新统计
            let mut stats = self.stats.write().await;
            stats.cache_stats.evictions += cleaned_count;
            
            info!("🧠 内存优化完成，清理过期缓存项: {}", cleaned_count);
        }
        
        Ok(())
    }
    
    /// 连接池统计更新
    pub async fn update_connection_pool_stats(&self, pool_stats: ConnectionPoolStats) {
        let mut stats = self.stats.write().await;
        stats.connection_pool_stats = pool_stats;
    }
    
    /// 更新内存统计
    pub async fn update_memory_stats(&self) {
        let mut stats = self.stats.write().await;
        
        // 这里可以集成实际的内存监控工具
        // 例如 jemalloc 或者 system allocator 的统计
        
        // 模拟内存统计更新
        #[cfg(target_os = "linux")]
        {
            if let Ok(info) = procfs::Meminfo::new() {
                // 在 Linux 上使用 /proc/meminfo
                stats.memory_stats.current_memory_usage = info.mem_total.saturating_sub(info.mem_available).as_bytes();
            }
        }
        
        // 更新峰值
        if stats.memory_stats.current_memory_usage > stats.memory_stats.peak_memory_usage {
            stats.memory_stats.peak_memory_usage = stats.memory_stats.current_memory_usage;
        }
    }
    
    /// 更新缓存统计
    async fn update_cache_stats(&self, hit: bool) {
        let mut stats = self.stats.write().await;
        if hit {
            stats.cache_stats.hits += 1;
        } else {
            stats.cache_stats.misses += 1;
        }
    }
    
    /// 启动定期性能优化任务
    pub async fn start_performance_monitor(&self) {
        let service = self.clone();
        
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(std::time::Duration::from_secs(300)); // 每5分钟执行一次
            
            loop {
                interval.tick().await;
                
                // 内存优化
                if let Err(e) = service.optimize_memory().await {
                    warn!("😨 内存优化失败: {}", e);
                }
                
                // 更新内存统计
                service.update_memory_stats().await;
                
                // 连接池健康检查
                if let Some(health_check) = &service.health_check {
                    if let Ok(status) = health_check.check_health().await {
                        info!("❤️ 系统健康状态: {:?}", status);
                    }
                }
                
                // 记录当前统计信息
                let stats = service.get_statistics().await;
                info!("📈 服务统计 - 请求: {}, 连接: {}, 缓存命中率: {:.2}%", 
                    stats.requests_handled, 
                    stats.active_connections,
                    stats.cache_stats.hit_rate * 100.0
                );
            }
        });
    }
    
    /// 获取服务健康状态
    pub async fn get_health_status(&self) -> ServerResult<HealthStatus> {
        let stats = self.get_statistics().await;
        let uptime = stats.start_time.elapsed().unwrap_or_default();
        
        let status = HealthStatus {
            healthy: true,
            uptime_seconds: uptime.as_secs(),
            active_connections: stats.active_connections,
            total_requests: stats.requests_handled,
            cache_hit_rate: stats.cache_stats.hit_rate,
            memory_usage_mb: stats.memory_stats.current_memory_usage / 1024 / 1024,
            last_check: SystemTime::now(),
        };
        
        Ok(status)
    }
}

/// 服务健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    pub healthy: bool,
    pub uptime_seconds: u64,
    pub active_connections: u32,
    pub total_requests: u64,
    pub cache_hit_rate: f64,
    pub memory_usage_mb: u64,
    pub last_check: SystemTime,
}

// 为 ConfigurationService 添加 Clone trait
impl Clone for ConfigurationService {
    fn clone(&self) -> Self {
        Self {
            storage: self.storage.clone(),
            encryption: self.encryption.clone(),
            audit: self.audit.clone(),
            cache: self.cache.clone(),
            notifier: self.notifier.clone(),
            authorization: self.authorization.clone(),
            health_check: self.health_check.clone(),
            broadcast_manager: self.broadcast_manager.clone(),
            stats: self.stats.clone(),
        }
    }
    
    /// 增加请求计数
    async fn increment_request_count(&self, success: bool, processing_time_ms: f64) {
        let mut stats = self.stats.write().await;
        stats.requests_handled += 1;
        
        if success {
            stats.successful_requests += 1;
        } else {
            stats.failed_requests += 1;
        }
        
        // 更新平均处理时间
        if stats.requests_handled == 1 {
            stats.avg_processing_time_ms = processing_time_ms;
        } else {
            stats.avg_processing_time_ms = 
                (stats.avg_processing_time_ms * (stats.requests_handled - 1) as f64 + processing_time_ms) 
                / stats.requests_handled as f64;
        }
    }
    
    /// 增加连接数
    async fn increment_connection_count(&self) {
        let mut stats = self.stats.write().await;
        stats.active_connections += 1;
    }
    
    /// 减少连接数
    async fn decrement_connection_count(&self) {
        let mut stats = self.stats.write().await;
        if stats.active_connections > 0 {
            stats.active_connections -= 1;
        }
    }
    
    /// 获取配置
    async fn get_configuration(
        &self,
        environment: &ConfigEnvironment,
        user: Option<&str>,
    ) -> ServerResult<ConfigurationData> {
        let start_time = SystemTime::now();
        let mut cache_hit = false;
        
        let result = async {
            // 权限检查
            if let (Some(auth), Some(user)) = (&self.authorization, user) {
                if !auth.can_read(user, environment).await? {
                    return Err(ConfigurationServerError::AuthorizationError(
                        format!("用户 {} 无权读取配置 {:?}", user, environment)
                    ));
                }
            }
            
            // 尝试从缓存获取
            if let Some(cache) = &self.cache {
                if let Ok(Some(data)) = cache.get(environment).await {
                    if !cache.is_expired(environment).await.unwrap_or(true) {
                        cache_hit = true;
                        info!("💾 从缓存获取配置: {:?}", environment);
                        return Ok(data);
                    }
                }
            }
            
            // 从存储加载配置
            let mut data = self.storage.load(environment).await?;
            
            // 解密敏感配置
            if let Some(encryption) = &self.encryption {
                encryption.decrypt(&mut data.config).await?;
            }
            
            // 更新缓存
            if let Some(cache) = &self.cache {
                if let Err(e) = cache.put(&data).await {
                    warn!("💾 更新缓存失败: {}", e);
                }
            }
            
            info!("✅ 成功获取配置: {:?}", environment);
            Ok(data)
        }.await;
        
        // 统计更新
        let processing_time = start_time.elapsed().unwrap_or_default().as_millis() as f64;
        let success = result.is_ok();
        
        self.increment_request_count(success, processing_time).await;
        self.update_cache_stats(cache_hit).await;
        
        result
    }
    
    /// 保存配置
    async fn save_configuration(
        &self,
        mut data: ConfigurationData,
        user: &str,
    ) -> ServerResult<String> {
        // 权限检查
        if let Some(auth) = &self.authorization {
            if !auth.can_write(user, &data.environment).await? {
                return Err(ConfigurationServerError::AuthorizationError(
                    format!("用户 {} 无权写入配置 {:?}", user, data.environment)
                ));
            }
        }
        
        // 获取旧配置用于审计
        let old_config = self.storage.load(&data.environment).await.ok();
        
        // 加密敏感配置
        if let Some(encryption) = &self.encryption {
            encryption.encrypt(&mut data.config).await?;
        }
        
        // 保存到存储
        let version = self.storage.save(&data, user).await?;
        data.version = version.clone();
        
        // 清除缓存
        if let Some(cache) = &self.cache {
            if let Err(e) = cache.remove(&data.environment).await {
                warn!("清除缓存失败: {}", e);
            }
        }
        
        // 记录审计日志
        if let Some(audit) = &self.audit {
            let change = ConfigurationChange {
                id: uuid::Uuid::new_v4().to_string(),
                environment: data.environment.clone(),
                operation: if old_config.is_some() { ChangeOperation::Update } else { ChangeOperation::Create },
                user: user.to_string(),
                timestamp: SystemTime::now(),
                description: format!(
                    "{} 配置 {:?}", 
                    if old_config.is_some() { "更新" } else { "创建" },
                    data.environment
                ),
                old_config: old_config.map(|d| d.config),
                new_config: Some(data.config.clone()),
                details: HashMap::new(),
            };
            
            if let Err(e) = audit.log_change(&change).await {
                warn!("记录审计日志失败: {}", e);
            }
        }
        
        // 发送变更通知
        if let Some(notifier) = &self.notifier {
            let event = ConfigurationEvent {
                event_type: if old_config.is_some() { EventType::ConfigurationUpdated } else { EventType::ConfigurationCreated },
                environment: data.environment.clone(),
                data: Some(data.clone()),
                timestamp: SystemTime::now(),
                metadata: HashMap::new(),
            };
            
            if let Err(e) = notifier.notify(event).await {
                warn!("发送变更通知失败: {}", e);
            }
        }
        
        // 🆕 新增：发送配置广播事件
        #[cfg(feature = "broadcast")]
        if let Some(broadcast_manager) = &self.broadcast_manager {
            // 根据操作类型发送不同的广播事件
            let broadcast_result = if old_config.is_some() {
                // 配置更新事件
                broadcast_manager.broadcast_config_update(
                    &data.environment.application,
                    &data.environment.profile,
                    data.environment.label.as_deref(),
                    &format!("{}", data.environment.application), // 配置路径
                    old_config.as_ref().map(|d| serde_json::to_value(&d.config).unwrap_or_default()),
                    serde_json::to_value(&data.config).unwrap_or_default(),
                    Some(user),
                ).await
            } else {
                // 配置创建事件（作为更新事件处理）
                broadcast_manager.broadcast_config_update(
                    &data.environment.application,
                    &data.environment.profile,
                    data.environment.label.as_deref(),
                    &format!("{}", data.environment.application),
                    None,
                    serde_json::to_value(&data.config).unwrap_or_default(),
                    Some(user),
                ).await
            };
            
            if let Err(e) = broadcast_result {
                warn!("📡 发送配置广播事件失败: {}", e);
            } else {
                info!("🎆 配置广播事件发送成功: {:?}", data.environment);
            }
        }
        
        // 广播配置更新事件
        if let Some(broadcast_manager) = &self.broadcast_manager {
            let config_path = format!("{}.{}.{}", 
                data.environment.application,
                data.environment.profile, 
                data.environment.label.as_deref().unwrap_or("default")
            );
            
            let old_value = old_config.as_ref()
                .and_then(|c| serde_json::to_value(&c.config).ok());
            let new_value = serde_json::to_value(&data.config)
                .unwrap_or(serde_json::Value::Null);
                
            if let Err(e) = broadcast_manager.broadcast_config_update(
                &data.environment.application,
                &data.environment.profile,
                data.environment.label.as_deref(),
                &config_path,
                old_value,
                new_value,
                Some(user),
            ).await {
                warn!("广播配置更新事件失败: {}", e);
            } else {
                info!("✨ 成功广播配置更新事件: {}", config_path);
            }
        }
        
        info!("成功保存配置: {:?} -> {}", data.environment, version);
        Ok(version)
    }
    
    /// 删除配置
    async fn delete_configuration(
        &self,
        environment: &ConfigEnvironment,
        user: &str,
    ) -> ServerResult<()> {
        // 权限检查
        if let Some(auth) = &self.authorization {
            if !auth.can_delete(user, environment).await? {
                return Err(ConfigurationServerError::AuthorizationError(
                    format!("用户 {} 无权删除配置 {:?}", user, environment)
                ));
            }
        }
        
        // 获取配置用于审计
        let old_config = self.storage.load(environment).await.ok();
        
        // 从存储删除
        self.storage.delete(environment, user).await?;
        
        // 清除缓存
        if let Some(cache) = &self.cache {
            if let Err(e) = cache.remove(environment).await {
                warn!("清除缓存失败: {}", e);
            }
        }
        
        // 记录审计日志
        if let Some(audit) = &self.audit {
            let change = ConfigurationChange {
                id: uuid::Uuid::new_v4().to_string(),
                environment: environment.clone(),
                operation: ChangeOperation::Delete,
                user: user.to_string(),
                timestamp: SystemTime::now(),
                description: format!("删除配置 {:?}", environment),
                old_config: old_config.map(|d| d.config),
                new_config: None,
                details: HashMap::new(),
            };
            
            if let Err(e) = audit.log_change(&change).await {
                warn!("记录审计日志失败: {}", e);
            }
        }
        
        // 发送删除通知
        if let Some(notifier) = &self.notifier {
            let event = ConfigurationEvent {
                event_type: EventType::ConfigurationDeleted,
                environment: environment.clone(),
                data: None,
                timestamp: SystemTime::now(),
                metadata: HashMap::new(),
            };
            
            if let Err(e) = notifier.notify(event).await {
                warn!("发送删除通知失败: {}", e);
            }
        }
        
        // 🆕 新增：发送配置删除广播事件
        #[cfg(feature = "broadcast")]
        if let Some(broadcast_manager) = &self.broadcast_manager {
            let broadcast_result = broadcast_manager.broadcast_config_delete(
                &environment.application,
                &environment.profile,
                environment.label.as_deref(),
                &format!("{}", environment.application), // 配置路径
                Some(user),
            ).await;
            
            if let Err(e) = broadcast_result {
                warn!("📡 发送配置删除广播事件失败: {}", e);
            } else {
                info!("🗑️ 配置删除广播事件发送成功: {:?}", environment);
            }
        }
        
        // 广播配置删除事件
        if let Some(broadcast_manager) = &self.broadcast_manager {
            let config_path = format!("{}.{}.{}", 
                environment.application,
                environment.profile, 
                environment.label.as_deref().unwrap_or("default")
            );
                
            if let Err(e) = broadcast_manager.broadcast_config_delete(
                &environment.application,
                &environment.profile,
                environment.label.as_deref(),
                &config_path,
                Some(user),
            ).await {
                warn!("广播配置删除事件失败: {}", e);
            } else {
                info!("✨ 成功广播配置删除事件: {}", config_path);
            }
        }
        
        info!("成功删除配置: {:?}", environment);
        Ok(())
    }
    
    /// 获取配置历史
    async fn get_configuration_history(
        &self,
        environment: &ConfigEnvironment,
        user: Option<&str>,
    ) -> ServerResult<Vec<ConfigurationChange>> {
        // 权限检查
        if let (Some(auth), Some(user)) = (&self.authorization, user) {
            if !auth.can_read(user, environment).await? {
                return Err(ConfigurationServerError::AuthorizationError(
                    format!("用户 {} 无权读取配置历史 {:?}", user, environment)
                ));
            }
        }
        
        let history = self.storage.get_history(environment).await?;
        info!("获取配置历史: {:?}, {} 条记录", environment, history.len());
        Ok(history)
    }
    
    /// 回滚配置
    async fn rollback_configuration(
        &self,
        environment: &ConfigEnvironment,
        version: &str,
        user: &str,
    ) -> ServerResult<()> {
        // 权限检查
        if let Some(auth) = &self.authorization {
            if !auth.can_write(user, environment).await? {
                return Err(ConfigurationServerError::AuthorizationError(
                    format!("用户 {} 无权回滚配置 {:?}", user, environment)
                ));
            }
        }
        
        // 执行回滚
        self.storage.rollback(environment, version, user).await?;
        
        // 清除缓存
        if let Some(cache) = &self.cache {
            if let Err(e) = cache.remove(environment).await {
                warn!("清除缓存失败: {}", e);
            }
        }
        
        // 记录审计日志
        if let Some(audit) = &self.audit {
            let change = ConfigurationChange {
                id: uuid::Uuid::new_v4().to_string(),
                environment: environment.clone(),
                operation: ChangeOperation::Rollback,
                user: user.to_string(),
                timestamp: SystemTime::now(),
                description: format!("回滚配置 {:?} 到版本 {}", environment, version),
                old_config: None,
                new_config: None,
                details: HashMap::new(),
            };
            
            if let Err(e) = audit.log_change(&change).await {
                warn!("记录审计日志失败: {}", e);
            }
        }
        
        // 广播配置回滚事件
        if let Some(broadcast_manager) = &self.broadcast_manager {
            let config_path = format!("{}.{}.{}", 
                environment.application,
                environment.profile, 
                environment.label.as_deref().unwrap_or("default")
            );
                
            // 回滚作为配置更新事件处理
            if let Err(e) = broadcast_manager.broadcast_config_update(
                &environment.application,
                &environment.profile,
                environment.label.as_deref(),
                &config_path,
                None, // 旧值未知
                serde_json::Value::String(format!("回滚到版本: {}", version)),
                Some(user),
            ).await {
                warn!("广播配置回滚事件失败: {}", e);
            } else {
                info!("✨ 成功广播配置回滚事件: {} -> {}", config_path, version);
            }
        }
        
        info!("成功回滚配置: {:?} -> {}", environment, version);
        
        // 🆕 新增：发送配置刷新广播事件（回滚也是一种配置变更）
        #[cfg(feature = "broadcast")]
        if let Some(broadcast_manager) = &self.broadcast_manager {
            let broadcast_result = broadcast_manager.broadcast_config_refresh(
                &environment.application,
                &environment.profile,
                None, // 广播给所有服务
            ).await;
            
            if let Err(e) = broadcast_result {
                warn!("📡 发送配置回滚广播事件失败: {}", e);
            } else {
                info!("♾️ 配置回滚广播事件发送成功: {:?} -> {}", environment, version);
            }
        }
        Ok(())
    }
}

#[async_trait]
impl ConfigurationProvider for ConfigurationService {
    async fn get_configuration(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationData> {
        self.storage.load(environment).await
    }
    
    async fn exists(&self, environment: &ConfigEnvironment) -> ConfigurationResult<bool> {
        match self.storage.load(environment).await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }
    
    async fn list_applications(&self) -> ConfigurationResult<Vec<String>> {
        // 基本存储可能不支持列举，返回空列表
        // 如果需要列举功能，应该使用DatabaseStorageProvider
        Ok(vec![])
    }
    
    async fn list_profiles(&self, _application: &str) -> ConfigurationResult<Vec<String>> {
        // 基本存储可能不支持列举，返回空列表
        // 如果需要列举功能，应该使用DatabaseStorageProvider
        Ok(vec![])
    }
    
    async fn list_labels(&self, _application: &str, _profile: &str) -> ConfigurationResult<Vec<String>> {
        // 基本存储可能不支持列举，返回空列表
        // 如果需要列举功能，应该使用DatabaseStorageProvider
        Ok(vec![])
    }
}
/// 配置服务器主控制器
/// 
/// 负责整个配置服务器的生命周期管理，包括HTTP服务器、配置服务等
pub struct ConfigurationServer {
    /// 服务器配置
    config: ConfigurationServerConfig,
    /// 配置服务
    service: Arc<ConfigurationService>,
    /// HTTP服务器句柄
    server_handle: Option<tokio::task::JoinHandle<()>>,
}

impl ConfigurationServer {
    /// 创建配置服务器构建器
    pub fn builder() -> ServerBuilder {
        ServerBuilder::new()
    }
    
    /// 创建新的配置服务器
    pub fn new(
        config: ConfigurationServerConfig,
        service: Arc<ConfigurationService>,
    ) -> Self {
        Self {
            config,
            service,
            server_handle: None,
        }
    }
    
    /// 启动配置服务器
    pub async fn start(&mut self) -> ServerResult<()> {
        info!("🚀 启动配置服务器: {}", self.config.server_name);
        info!("📍 监听地址: {}", self.config.bind_address);
        
        // 初始化存储
        if let Err(e) = self.service.storage.initialize().await {
            error!("存储初始化失败: {}", e);
            return Err(ConfigurationServerError::StorageError(
                format!("存储初始化失败: {}", e)
            ));
        }
        
        // 创建HTTP服务器
        let app = api::create_routes(self.service.clone()).await
            .map_err(|e| ConfigurationServerError::ServerError(e.to_string()))?;
        
        // 启动HTTP服务器
        let listener = tokio::net::TcpListener::bind(&self.config.bind_address).await?;
        
        let server_handle = tokio::spawn(async move {
            if let Err(e) = axum::serve(listener, app).await {
                error!("HTTP服务器错误: {}", e);
            }
        });
        
        self.server_handle = Some(server_handle);
        
        info!("✅ 配置服务器已启动");
        Ok(())
    }
    
    /// 停止配置服务器
    pub async fn stop(&mut self) -> ServerResult<()> {
        info!("🛑 停止配置服务器");
        
        if let Some(handle) = self.server_handle.take() {
            handle.abort();
        }
        
        info!("✅ 配置服务器已停止");
        Ok(())
    }
    
    /// 获取服务器状态
    pub async fn get_status(&self) -> ServerResult<ServerStatus> {
        let health = if let Some(health_check) = &self.service.health_check {
            health_check.check_health().await.unwrap_or_else(|_| HealthStatus {
                healthy: false,
                uptime_seconds: 0,
                active_connections: 0,
                total_requests: 0,
                cache_hit_rate: 0.0,
                memory_usage_mb: 0,
                last_check: SystemTime::now(),
            })
        } else {
            HealthStatus {
                healthy: true,
                uptime_seconds: SystemTime::now().duration_since(self.service.stats.read().await.start_time).unwrap_or_default().as_secs(),
                active_connections: self.service.stats.read().await.active_connections,
                total_requests: self.service.stats.read().await.requests_handled,
                cache_hit_rate: 0.0,
                memory_usage_mb: 0,
                last_check: SystemTime::now(),
            }
        };
        
        let stats = self.service.get_statistics().await;
        
        Ok(ServerStatus {
            name: self.config.server_name.clone(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            status: health,
            uptime: SystemTime::now(),
            connections: stats.active_connections,
            requests_handled: stats.requests_handled,
        })
    }
    
    /// 获取配置服务
    pub fn service(&self) -> &Arc<ConfigurationService> {
        &self.service
    }
}

/// 服务器状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerStatus {
    /// 服务器名称
    pub name: String,
    /// 版本号
    pub version: String,
    /// 健康状态
    pub status: HealthStatus,
    /// 启动时间
    pub uptime: SystemTime,
    /// 当前连接数
    pub connections: u32,
    /// 已处理请求数
    pub requests_handled: u64,
}

/// 配置服务器构建器
pub struct ServerBuilder {
    config: ConfigurationServerConfig,
    storage: Option<Arc<dyn ConfigurationStorage>>,
    encryption: Option<Arc<dyn ConfigurationEncryption>>,
    audit: Option<Arc<dyn ConfigurationAudit>>,
    cache: Option<Arc<dyn ConfigurationCache>>,
    notifier: Option<Arc<dyn ConfigurationNotifier>>,
    authorization: Option<Arc<dyn ConfigurationAuthorization>>,
    health_check: Option<Arc<dyn ConfigurationHealthCheck>>,
    broadcast_manager: Option<Arc<dyn ConfigBroadcastManager>>,
}

impl ServerBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            config: ConfigurationServerConfig::default(),
            storage: None,
            encryption: None,
            audit: None,
            cache: None,
            notifier: None,
            authorization: None,
            health_check: None,
            broadcast_manager: None,
        }
    }
    
    /// 设置服务器配置
    pub fn with_config(mut self, config: ConfigurationServerConfig) -> Self {
        self.config = config;
        self
    }
    
    /// 设置绑定地址
    pub fn bind<A: std::net::ToSocketAddrs>(mut self, addr: A) -> Self {
        if let Ok(mut addrs) = addr.to_socket_addrs() {
            if let Some(addr) = addrs.next() {
                self.config.bind_address = addr;
            }
        }
        self
    }
    
    /// 设置服务器名称
    pub fn with_name(mut self, name: &str) -> Self {
        self.config.server_name = name.to_string();
        self
    }
    
    /// 设置存储后端
    pub fn with_storage(mut self, storage: Arc<dyn ConfigurationStorage>) -> Self {
        self.storage = Some(storage);
        self
    }
    
    /// 设置加密组件
    pub fn with_encryption(mut self, encryption: Arc<dyn ConfigurationEncryption>) -> Self {
        self.encryption = Some(encryption);
        self
    }
    
    /// 设置审计组件
    pub fn with_audit(mut self, audit: Arc<dyn ConfigurationAudit>) -> Self {
        self.audit = Some(audit);
        self
    }
    
    /// 设置缓存组件
    pub fn with_cache(mut self, cache: Arc<dyn ConfigurationCache>) -> Self {
        self.cache = Some(cache);
        self
    }
    
    /// 设置通知组件
    pub fn with_notifier(mut self, notifier: Arc<dyn ConfigurationNotifier>) -> Self {
        self.notifier = Some(notifier);
        self
    }
    
    /// 设置权限控制组件
    pub fn with_authorization(mut self, authorization: Arc<dyn ConfigurationAuthorization>) -> Self {
        self.authorization = Some(authorization);
        self
    }
    
    /// 设置健康检查组件
    pub fn with_health_check(mut self, health_check: Arc<dyn ConfigurationHealthCheck>) -> Self {
        self.health_check = Some(health_check);
        self
    }
    
    /// 启用认证
    pub fn enable_auth(mut self, jwt_secret: &str) -> Self {
        self.config.enable_auth = true;
        self.config.jwt_secret = Some(jwt_secret.to_string());
        self
    }
    
    /// 设置缓存TTL
    pub fn with_cache_ttl(mut self, ttl: u64) -> Self {
        self.config.cache_ttl = ttl;
        self
    }
    
    /// 构建配置服务器
    pub async fn build(self) -> ServerResult<ConfigurationServer> {
        // 验证必需组件
        let storage = self.storage.ok_or_else(|| {
            ConfigurationServerError::ServerError("存储后端未配置".to_string())
        })?;
        
        // 创建配置服务
        let mut service = ConfigurationService::new(storage);
        
        if let Some(encryption) = self.encryption {
            service = service.with_encryption(encryption);
        }
        
        if let Some(audit) = self.audit {
            service = service.with_audit(audit);
        }
        
        if let Some(cache) = self.cache {
            service = service.with_cache(cache);
        }
        
        if let Some(notifier) = self.notifier {
            service = service.with_notifier(notifier);
        }
        
        if let Some(authorization) = self.authorization {
            service = service.with_authorization(authorization);
        }
        
        if let Some(health_check) = self.health_check {
            service = service.with_health_check(health_check);
        }
        
        let server = ConfigurationServer::new(
            self.config,
            Arc::new(service),
        );
        
        Ok(server)
    }
}

impl Default for ServerBuilder {
    fn default() -> Self {
        Self::new()
    }
}


















